
#ifndef CENTRANCE_HTTP_CLIENT_H_
#define CENTRANCE_HTTP_CLIENT_H_

#include "CNetworkServiceHeader.h"
#include "CcmdBase.h"
#include "CControlTool.h"

/**************************************************************************
Date: 2021-12-31
Description: HTTP
门禁HTTP 客服端实现
**************************************************************************/

NETWORKSERVICE_BEGIN_NAMESPACE
typedef struct _tpullFileRtn{
    XJSON_FUNCI

    // 返回码
    int code;

    // 返回消息
    string msg;

    // 返回数据
    string data;

    _tpullFileRtn(){
		code = -1;
	}
    XPACK( O(code, msg, data));
}T_pullFileRtn;

#define HTTP_CLINET_LOG
class NETWORKSERVICE_API CEntranceHttpClient{
public:
	CEntranceHttpClient(){}
	~CEntranceHttpClient(){}
	// http请求

	template <class HandleSendType,class HandleRecvType>
	bool request(struct tRouteData<HandleSendType> *send,struct tRouteData<HandleRecvType> *recv)
	{
		bool ret = false;
		if(!send){
			return false;
		}
		tsReqData msg;
		MAP_PARAMS headParams;
		headParams["sn"] = send->msg.sn;
		headParams["timestamp"] = std::to_string(send->msg.timestamp);
		headParams["sendMsgId"] = send->msg.sendMsgId;
		headParams["appKey"] = send->msg.appKey;
		headParams["signature"] = send->msg.signature;
		headParams["Content-Type"] = "application/json;charset=utf-8";
        string sendData;
        ret = send->msg.toJsonString(sendData);
		if(!ret){
			return false;
		}
#ifdef HTTP_CLINET_LOG
        qDebug("httpReq:url=%s,send %s", send->route.httpClientInfo.url.c_str(), sendData.c_str());
#endif
		try{
			// http请求
			msg = CHttpClient::httpReq( send->route.httpClientInfo.method,
										send->route.httpClientInfo.url.c_str(),
										NULL,
										&headParams,
										sendData,
										send->route.httpClientInfo.conTimeout,
										send->route.httpClientInfo.recvTimeout);
		}catch (...){
            qDebug("CHttpClient::httpReq error:url=%s, boody=%s",send->route.httpClientInfo.url.c_str(),sendData.c_str());
			if(recv){
				recv->route.type = ROUTE_HTTP_SERVICE;
				return false;
			}
			return false;
		}
#ifdef HTTP_CLINET_LOG
        qDebug("httpReq:recv %s",msg.msg.c_str());
#endif
		if(!recv){
			return msg.status;
		}
		if(!msg.status){
			return false;
		}

		recv->route.type = ROUTE_HTTP_SERVICE;
        ret = recv->msg.loadJsonString(msg.msg);
		if(!ret){
			return false;
		}
		return true;

	}

	T_pullFileRtn pullFile(struct tRouteData<T_NullData> *send, string fileName, string filePath);

	int downFile(string url,string savePath)
	{
		return CHttpFile::downFile(3*1024*1024, url,savePath);
	}
	string downFile(string url,string saveDir, bool isautoFileType)
	{
		return CHttpFile::downFileToDir(3*1024*1024, url, saveDir, isautoFileType);
	}
};

NETWORKSERVICE_END_NAMESPACE

#endif // CENTRANCE_HTTP_CLIENT_H_
